import SendMessage from "../message/SendMessage";
import Service from "./Service";
export default class WebSocketService extends Service{
    protected socket;


    destroy(){
        if(this.socket != null){
            this.socket.close();
            this.socket = null;
        }
    }
    //手动重联
    reConnect(){
        this.connect(this.url,this.port);
    }

    onData(event){
        super.onData(event.data);
    }  

    connect(url:string,port?:number){
        super.connect(url,port);
        this.destroy();
        try{
            let self = this 
            this.socket = new WebSocket(this.url);
            this.socket.binaryType = "arraybuffer";
            this.socket.onopen = function (event) {
                self.onOpen(event);
            };
            this.socket.onmessage = function (event) {
                self.onData(event);
            };
            this.socket.onerror = function (event) {
                self.onError(event);
            };
            this.socket.onclose = function (event) {
                self.onClose(event);
            };           
        }catch(error){
            cc.log("WebService connect error "+error);
        } 
    }

    sendData(message:SendMessage){
        if(this.isReady() && this.socket){
            this.socket.send(message.getData());
        } else {
            cc.warn(" 请先连接服务器 ",this.url);
        }            
    }


   
}
